package com.chianghao.rock.account.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.chianghao.auth.Config;
import com.chianghao.auth.core.token.ITokenHandle;
import com.chianghao.auth.core.token.model.JWTToken;
import com.chianghao.auth.web.RequestContext;
import com.chianghao.core.utils.CollectionUtils;
import com.chianghao.core.web.R;
import com.chianghao.rock.Constant;
import com.chianghao.rock.account.model.UserInfo;
import com.chianghao.rock.admin.system.login.vo.LoginUserInfoVo;
import com.chianghao.rock.admin.system.route.vo.RoutersMateVo;
import com.chianghao.rock.admin.system.route.vo.RoutersVo;
import com.chianghao.rock.system.entity.Role;
import com.chianghao.rock.system.entity.Route;
import com.chianghao.rock.system.entity.User;
import com.chianghao.rock.system.service.role_scope.RoleScopeService;
import com.chianghao.rock.system.service.route.RouteService;
import com.chianghao.rock.system.service.user.UserService;
import com.chianghao.rock.system.service.user_role.UserRoleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value = "登录", tags = "登录")
public class LoginController {

	@Autowired
	UserService userService;
	
	@Autowired
	UserRoleService userRoleService;
	
	@Autowired
	RoleScopeService roleScopeService;
	
	@Autowired 
	RouteService routeService;
	
	@Autowired
	ITokenHandle<JWTToken> tokenHandle;
	
	@ApiOperation("登录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account",value = "账号",paramType = "query",required = true,dataType = "String"),
		@ApiImplicitParam(name = "password",value = "密码",paramType = "query",required = true,dataType = "String")
	})
	@PostMapping("login")
	public R<String> login(
			@RequestParam("account") @NotNull(message="error:account,not.null") String account,
			@RequestParam("password") @NotNull(message="error:password,not.null") String password
			) {
		User user = userService.login(account,password);
		UserInfo userInfo  = new UserInfo(user.getId().toString());
		
		JWTToken token  = new JWTToken();
		// 设置用户
		token.setSub(userInfo.getCode());
		// 设置过期时间
		token.setExp(new Date((System.currentTimeMillis()+Config.tokenOutTime.get())));
		
		String tokenString = tokenHandle.getToken(token);
		
		return R.getSuccess(tokenString);
	}
	
	@ApiOperation("登录用户信息")
	@GetMapping("login/user-info")
	public R<LoginUserInfoVo> getLoginUserInfo(){
		Long userId  = Long.parseLong(RequestContext.getUserId());
	    User user  = userService.queryOneById(userId);
	    LoginUserInfoVo vo = new LoginUserInfoVo();
	    vo.setName(user.getName());
	    if(StringUtils.isEmpty(user.getAvatar())) {
	    	vo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
	    }
	    
	    List<Route> routeList = null;
	    //查询用户的所有角色
	    if(user.getIsSupperAdmin().intValue()==1) {
	    	vo.setRoles(CollectionUtils.arrayToList(Constant.supperAdmin));
	    	routeList = routeService.queryAllRoute();
	    }else {
	    	List<Role> list  = userRoleService.queryByUserId(userId);
	    	List<Long> rouleIds  = list.stream().map(item->item.getId()).collect(Collectors.toList());
	    	List<String> rouleIdsString  = rouleIds.stream().map(item->item.toString()).collect(Collectors.toList());
	    	vo.setRoles(rouleIdsString);
	    	routeList = roleScopeService.queryByRoleIds(rouleIds);
	    }
	    List<RoutersVo> listTree  = toRoutersDto(routeList, Constant.rootId);
	    vo.setRouters(listTree);
	    
	    return R.getSuccess(vo);
	}
	
	
	public  List<RoutersVo> toRoutersDto(List<Route> items,Long parentId){
		List<RoutersVo> list = new ArrayList<RoutersVo>();
    	for(Route bean:items) {
    		if(bean.getParentId().longValue()==parentId.longValue()) {
    			RoutersVo dto = new RoutersVo();
				if(dto!=null) {
					dto.setParentId(bean.getParentId());
					dto.setName(bean.getCode());
					dto.setComponent(bean.getCode());
					dto.setMeta(new RoutersMateVo(bean.getLanguateKey(),bean.getIcon()));
//					dto.setPath(bean.getShortRouteName());
					dto.setPath(bean.getRoute());
	    			List<RoutersVo> childList  = toRoutersDto(items,bean.getId());
	    			if(childList!=null&&!childList.isEmpty()) {
	    				dto.setChildren(childList);
	    			}
	    			list.add(dto);
				}
    		}
    	}
    	return list;
	}
	
	
	@ApiOperation("登录用户信息")
	@GetMapping("login/user-route")
	public R<List<RoutersVo>> getLoginUserRoute(){
		Long userId  = Long.parseLong(RequestContext.getUserId());
	    User user  = userService.queryOneById(userId);
	    List<Route> routeList = null;
	    //查询用户的所有角色
	    if(user.getIsSupperAdmin().intValue()==1) {
	    	routeList = routeService.queryAllRoute();
	    }else {
	    	List<Role> list  = userRoleService.queryByUserId(userId);
	    	List<Long> rouleIds  = list.stream().map(item->item.getId()).collect(Collectors.toList());
	    	routeList = roleScopeService.queryByRoleIds(rouleIds);
	    }
	    
	    List<RoutersVo> listTree  = toRoutersDto(routeList, Constant.rootId);
	    return R.getSuccess(listTree);
	}
	
	@ApiOperation("退出")
	@PostMapping("logout")
	public R<Boolean> logOut(){
		tokenHandle.removeToken(RequestContext.getToken().getId());
		return R.getSuccess(true);
	}
	
}
